package twel.probenprophet.helden.heroes.helden5;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.inject.Inject;

import twel.probenprophet.base.exceptions.ProbenprophetException;
import twel.probenprophet.helden.heroes.helden5.jaxb.Hero;

public class ZippedHeroesLoader {

	private final HeroXmlLoader heroXmlLoader;

	@Inject
	public ZippedHeroesLoader(HeroXmlLoader heroXmlLoader) {
		this.heroXmlLoader = heroXmlLoader;
	}

	public Collection<Hero> loadFromZipFile(String heldenZipPath) {
		ZipFile zipFile = null;
		try {
			zipFile = new ZipFile(heldenZipPath);
			return loadHeroesInZipFile(zipFile);

		} catch (IOException e) {
			throw new ProbenprophetException("could not open zip file", e);
		} finally {
			close(zipFile);
		}
	}

	private Collection<Hero> loadHeroesInZipFile(ZipFile zipFile) throws IOException {
		List<Hero> heroes = new ArrayList<Hero>();

		for (Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); zipEntries.hasMoreElements();) {
			ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();
			addHeroesToList(heroes, zipFile, zipEntry);
		}

		return heroes;
	}

	private void addHeroesToList(List<Hero> heroes, ZipFile zipFile, ZipEntry zipEntry) throws IOException {
		if (isAnXmlFile(zipEntry)) {
			InputStream inputStream = zipFile.getInputStream(zipEntry);
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

			Hero hero = heroXmlLoader.load(inputStreamReader);
			heroes.add(hero);
		}
	}

	private boolean isAnXmlFile(ZipEntry zipEntry) {
		String zippedFileName = zipEntry.getName();
		return zippedFileName.endsWith(".xml");
	}

	private void close(ZipFile zipFile) {
		if (zipFile != null) {
			try {
				zipFile.close();
			} catch (IOException e) {
				throw new ProbenprophetException("could not close zip file", e);
			}
		}
	}
}
